package com.huai.jt1078.handler.thread;

import com.huai.jt1078.config.VideoConfig;

import com.huai.jt1078.utils.SessionManager;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacpp.Loader;

import java.io.IOException;

/**
 * @author xingkong
 * @program jt1078
 * @description 推送视频流到RTMP线程 - 守护线程
 * @date 2023-01-04 21:11
 *
 * （通过ffmpeg子进程将http-flv另外传输一份到RTMP服务器的实现）
 **/
@Slf4j
public class PushVideoThread extends Thread{

    VideoConfig videoConfig;

    private final String tag;
    Process process = null;


    private final boolean saveHistory;

    public PushVideoThread(String tag,VideoConfig videoConfig) {
        this.tag = tag;
        this.videoConfig=videoConfig;
        saveHistory =videoConfig.isHistorySave() ;
    }

    @SneakyThrows
    @Override
    public void run() {

        String ffmpeg = Loader.load(org.bytedeco.ffmpeg.ffmpeg.class);
        ProcessBuilder realTime = null;

            String rtmpUrl = String.format(videoConfig.getRtmpUrl(),tag);
            realTime = new ProcessBuilder(
                    ffmpeg,"-re","-i",
                    "http://localhost:"+videoConfig.getHttpPort()+"/video/"+tag,
                    "-vcodec","copy","-acodec","aac",
                    "-loglevel","error",
                    "-f","flv",rtmpUrl);
            try {
                realTime.inheritIO().start();
                if (saveHistory){
                    log.info("{}正在保存录像",tag);
                    ProcessBuilder save = new ProcessBuilder(
                            ffmpeg,"-re", "-i", rtmpUrl,
                            "-loglevel","error",
                            "-c","copy",videoConfig.getHistoryPath()+tag+".mp4");
                    save.inheritIO().start();
                }
            }catch (IOException e){
                log.error("---------------IO异常:{}-----------",tag,e);
            }catch (Exception e){
                log.error("-----------推送失败:{}-------------",tag,e);
            }


            //log.info("flv播放地址:{},rtmp播放地址{}" , videoConfig.getFlvUrl(),rtmpUrl);
            //log.info("---------启动推送线程成功-------");
            SessionManager.instance.getProcessMap().put(tag,process);



    }
}
